document.addEventListener('DOMContentLoaded', () => {
    // 检查登录状态
    const token = localStorage.getItem('token');
    if (!token) {
        window.location.href = 'login.html';
        return;
    }

    // 显示用户名
    const user = JSON.parse(localStorage.getItem('user'));
    if (user) {
        document.getElementById('username').textContent = user.username;
    }

    let games = []; // 存储游戏数据的全局变量

    const gameContainer = document.getElementById('gameContainer');
    const searchInput = document.getElementById('searchInput');
    const searchBtn = document.getElementById('searchBtn');
    const priceRange = document.getElementById('priceRange');
    const priceValue = document.getElementById('priceValue');
    const genreFilters = document.querySelectorAll('#genreFilter input');

    // 添加鼠标跟随特效
    const emojis = ['🎮', '⭐', '🎯', '🎲', '🎪', '🎨', '🎭', '🎪', '🎫', '🎗'];
    let lastEmojiTime = 0;
    const EMOJI_INTERVAL = 100; // 控制表情生成频率（毫秒）

    document.addEventListener('mousemove', (e) => {
        const currentTime = Date.now();
        if (currentTime - lastEmojiTime > EMOJI_INTERVAL) {
            createEmoji(e.clientX, e.clientY);
            lastEmojiTime = currentTime;
        }
    });

    function createEmoji(x, y) {
        const emoji = document.createElement('div');
        emoji.className = 'cursor-emoji';
        emoji.textContent = emojis[Math.floor(Math.random() * emojis.length)];
        
        // 随机旋转角度
        const rotation = Math.random() * 360;
        // 随机移动方向
        const moveX = (Math.random() - 0.5) * 60;
        
        emoji.style.left = `${x}px`;
        emoji.style.top = `${y}px`;
        emoji.style.transform = `rotate(${rotation}deg)`;

        document.body.appendChild(emoji);

        // 添加一些随机移动
        requestAnimationFrame(() => {
            emoji.style.transform = `translate(${moveX}px, -100px) rotate(${rotation}deg) scale(1.5)`;
        });

        // 动画结束后移除元素
        setTimeout(() => {
            emoji.remove();
        }, 1000);
    }

    // 为游戏卡片添加悬停特效
    function addHoverEffect(card) {
        card.addEventListener('mouseover', (e) => {
            const rect = card.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;
            
            // 创建光晕效果
            const glowEffect = document.createElement('div');
            glowEffect.className = 'glow-effect';
            glowEffect.style.left = `${x}px`;
            glowEffect.style.top = `${y}px`;
            
            card.appendChild(glowEffect);
            
            setTimeout(() => {
                glowEffect.remove();
            }, 1000);
        });
    }

    // 渲染游戏卡片
    function renderGame(game) {
        const card = document.createElement('div');
        card.className = 'game-card';
        card.innerHTML = `
            <img src="${game.image_url}" alt="${game.title}" class="game-image">
            <div class="game-info">
                <h3 class="game-title">${game.title}</h3>
                <div class="game-meta">
                    <span class="game-price">¥${game.price}</span>
                    <span class="game-rating">★${game.rating || 0}</span>
                </div>
                <div class="game-tags">
                    ${game.tags.map(tag => `<span class="game-tag">${tag}</span>`).join('')}
                </div>
            </div>
        `;
        
        // 添加点击事件
        card.addEventListener('click', () => {
            window.location.href = `game-detail.html?id=${game.id}`;
        });
        
        // 添加悬停特效
        addHoverEffect(card);
        
        return card;
    }

    // 渲染所有游戏
    function renderGames(gamesToRender) {
        gameContainer.innerHTML = '';
        gamesToRender.forEach(game => {
            gameContainer.appendChild(renderGame(game));
        });
    }

    // 获取游戏列表
    async function fetchGames() {
        try {
            const response = await fetch('http://localhost:3000/api/games');
            games = await response.json(); // 保存到全局变量
            renderGames(games);
        } catch (error) {
            console.error('获取游戏列表失败:', error);
        }
    }

    // 搜索功能
    function handleSearch() {
        const searchTerm = searchInput.value.toLowerCase();
        const filteredGames = games.filter(game => 
            game.title.toLowerCase().includes(searchTerm) ||
            game.tags.some(tag => tag.toLowerCase().includes(searchTerm))
        );
        renderGames(filteredGames);
    }

    searchBtn.addEventListener('click', handleSearch);
    searchInput.addEventListener('keyup', (e) => {
        if (e.key === 'Enter') handleSearch();
    });

    // 价格范围筛选
    priceRange.addEventListener('input', () => {
        const maxPrice = priceRange.value;
        priceValue.textContent = `¥0 - ¥${maxPrice}`;
        const filteredGames = games.filter(game => game.price <= maxPrice);
        renderGames(filteredGames);
    });

    // 类型筛选
    function handleGenreFilter() {
        const selectedGenres = Array.from(genreFilters)
            .filter(input => input.checked)
            .map(input => input.value);

        const filteredGames = selectedGenres.length === 0 
            ? games 
            : games.filter(game => 
                game.genres.some(genre => selectedGenres.includes(genre))
            );

        renderGames(filteredGames);
    }

    genreFilters.forEach(filter => {
        filter.addEventListener('change', handleGenreFilter);
    });

    // 退出登录
    document.getElementById('logoutBtn').addEventListener('click', () => {
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        window.location.href = 'login.html';
    });

    // 初始化获取游戏列表
    fetchGames();
}); 